package view;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import model.DB;
import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.blackberry.api.homescreen.HomeScreen;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import lib.Util;
import lib.classes.Profile;
import lib.gui.LoginScreen;
import lib.gui.ScreenTemplate;

public class Mingle extends ScreenTemplate
{

	public Mingle() 
	{
		super("Mingle", true);
		// Determine if an SDCard is present 
        boolean sdCardPresent = false;
        String root = null;
        Enumeration e = FileSystemRegistry.listRoots();
        while (e.hasMoreElements())
        {
            root = (String)e.nextElement();
            if(root.equalsIgnoreCase("sdcard/"))
            {
                sdCardPresent = true;
            }     
        }            
        if(!sdCardPresent)
        {
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    Dialog.alert("This application requires an SD card to be present. Exiting application...");
                    System.exit(0);            
                } 
            });        
        }else
        {
			if(isRegistered())
			{
				//Load Profile
				switchScreen(new LoginScreen());
			}else
			{			
				String warning_text = "Agreement texts go here ....";
				LabelField warning = new LabelField(warning_text, USE_ALL_WIDTH);
				warning.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.WHITE, 50));
				ButtonField agree = new ButtonField("I Agree");
				agree.setChangeListener(new FieldChangeListener() 
				{
					public void fieldChanged(Field field, int context) 
					{
						//GetBuildings request = new GetBuildings();
						//PleaseWaitPopupScreen.showScreenAndWait(request, "Populating Buildings ... Please wait");
						//switchScreen(new MapYorkMain());
						switchScreen(new LoginScreen());
					}
				});
				ButtonField disagree = new ButtonField("I Do Not Agree");
				disagree.setChangeListener(new FieldChangeListener() 
				{			
					public void fieldChanged(Field field, int context) 
					{
						System.exit(0);				
					}
				});
				
				LabelField ttle = new LabelField(" AGREEMENT ");
				HorizontalFieldManager _hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
				_hfm.setPadding(new XYEdges(5, 0, 2, 0));
				_hfm.add(ttle);
				//super.setBanner(_hfm);
				add(_hfm);
				
				HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
				hfm.add(agree);
				hfm.add(new LabelField("     "));
				hfm.add(disagree);
				hfm.setPadding(new XYEdges(5, 0, 2, 0));
				
				add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
				add(warning);
				add(hfm);
			}
			
		}
		
		
	}

	private boolean isRegistered() 
	{
		FileConnection fcon = null;
		boolean isRegistered = false;
		try{
			fcon = (FileConnection) Connector.open(Util.APPPATH+ Util.regFile );
			boolean deviceOnServer = deviceRegisteredOnServer(DeviceInfo.getDeviceId());
			if(fcon.exists() && deviceOnServer)
			{
				isRegistered = true;
			}/*else if(deviceOnServer && _db.rememberLogin())
			{
				isRegistered = true;
				initDB();
				Profile p = Util.updateDBFromServer(_db);
				if(p != null)
				{
					profile = p;
				}
			}*/
		}catch(Exception e)
		{
			System.out.println("Error @ isRegistered:: Error opening file");
		}
		return isRegistered;
	}
	
	public static boolean deviceRegisteredOnServer(int pin)
	{
		boolean isRegistered = false;
		ConnectionFactory connFact = new ConnectionFactory();
        ConnectionDescriptor connDesc;
        connDesc = connFact.getConnection(Util.Host(DB.serverURL, -1));
        if (connDesc != null)
        {
            HttpConnection httpConn;
            httpConn = (HttpConnection)connDesc.getConnection();
            try
            {
            	URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
            	encPostData.append("action", "findprofile");
            	encPostData.append("pin", DeviceInfo.getDeviceId()+"");
            	byte[] postDataBytes = encPostData.getBytes();
            	
            	httpConn.setRequestMethod(HttpConnection.POST);
            	httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            	httpConn.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
            	httpConn.setRequestProperty("Content-Language", "en-US");
            	httpConn.setRequestProperty("Content-Length",new Integer(postDataBytes.length).toString());
            	
            	int rc = httpConn.getResponseCode();
                if(rc == HttpConnection.HTTP_OK) {
                	OutputStream os = httpConn.openOutputStream();
                    os.write( postDataBytes );
                    InputStream is;
	                is = httpConn.openInputStream();
	                //is.read( _data );
	                Profile p = returnProfileFromXML(is);
	                if(p != null)
	                	isRegistered = true;   
                }
            }catch(Exception e)
            {
            	System.out.println(e.getMessage());
            }
        }
		return isRegistered;
	}
	
	public static Profile returnProfileFromXML(InputStream is)
	{
		try {
			Vector xmlVector = new Vector();
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            //InputStream inputStream = c.openInputStream();//getClass().getResourceAsStream( _xmlFileName );
            Document document = builder.parse( is );
            
            Element rootElement = document.getDocumentElement();
            rootElement.normalize();

            Util.displayNode(rootElement, new Vector(), xmlVector);
            System.out.println("PRINTOUT:: " + xmlVector.size());
            if(xmlVector.size() == 11)
            {
            	Profile p = new Profile(DeviceInfo.getDeviceId(), new Date(Long.parseLong((String)xmlVector.elementAt(6))), 
            		(String)xmlVector.elementAt(2), (String)xmlVector.elementAt(3),
            		(String)xmlVector.elementAt(4), (String)xmlVector.elementAt(5), 
            		(String)xmlVector.elementAt(8), (String)xmlVector.elementAt(9), 
            		(String)xmlVector.elementAt(10), false);
            	p.setPrivate(((String)xmlVector.elementAt(7)).toLowerCase().equals("true")?false:true);
            	return p;
            }
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return null;
	}
	
	
}
